package com.cs.beneficios.web.action;

import com.cs.beneficios.business.entity.CargueDAO;
import com.cs.beneficios.business.entity.VflexDAO;
import com.cs.beneficios.business.model.CargueVO;
import com.cs.beneficios.business.model.VflexVO;
import com.cs.beneficios.common.ConnectionFactory;
import com.cs.beneficios.web.form.StrutsUploadForm;
import com.cs.paoyer.administration.business.model.UserVO;
import com.cs.paoyer.administration.exception.AdministrationUserException;
import com.cs.paoyer.administration.util.AccessControl;
import com.cs.paoyer.common.exception.CommonUserException;
import com.cs.paoyer.common.exception.UserException;

import java.io.IOException;

import java.sql.SQLException;

import java.text.SimpleDateFormat;

import java.util.Calendar;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.upload.FormFile;


public class IngresarAction extends Action 
{
  /**
   * This is the main action called from the Struts framework.
   * @param mapping The ActionMapping used to select this instance.
   * @param form The optional ActionForm bean for this request.
   * @param request The HTTP Request we are processing.
   * @param response The HTTP Response we are processing.
   * @return 
   * @throws java.io.IOException
   * @throws javax.servlet.ServletException
   */
  public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
  {
      
      ActionMessages messages = new ActionMessages();
      
       try{
           AccessControl access = new AccessControl();
           access.validateAccess(mapping,request,response);
           
           //ConnectionFactory cf = new ConnectionFactory("beneficios","beneficios");
		   ConnectionFactory cf = new ConnectionFactory();
           HttpSession session = request.getSession();
           UserVO user = (UserVO) session.getAttribute("userInfo");
           String terminalAddress = "WEB="+request.getRemoteAddr();
           Calendar c = Calendar.getInstance(); 
           SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
                      
           String strnomcargue = request.getParameter("nombre_cargue");
           String strtipcargue = request.getParameter("tipo_cargue");
           String ingreso = request.getParameter("ingreso");
           List tipoCargue = null;
           //request.setCharacterEncoding("utf-8");
           System.getProperty("file.encoding");
           if((Object)ingreso != null)
           {
             if(ingreso.equals("true"))
             {
               try{
                  CargueVO objcargueVO = new CargueVO();
                   StrutsUploadForm myForm = (StrutsUploadForm)form;
                  // Process the FormFile
                  FormFile myFile = myForm.getTheFile();
                  String contentType = myFile.getContentType();
                  String fileName    = myFile.getFileName();
                  int fileSize       = myFile.getFileSize();
                  byte[] fileData   = myFile.getFileData();
                                   
                  /*System.out.println("contentType: " + contentType);
                  System.out.println("File Name: " + fileName);
                  System.out.println("File Size: " + fileSize);*/
                  
                  objcargueVO.setNombre(strnomcargue);
                  objcargueVO.setVflcodigo(strtipcargue);
                  objcargueVO.setArchivo(fileName);
                  
                  CargueDAO objcargueDAO = new CargueDAO(cf);
                  String retorno[] = objcargueDAO.ingresarCargue(objcargueVO,user.getName(),terminalAddress,dateFormat.format(c.getTime()));
                  cf.closeConnection(objcargueDAO.getConn());
                   if(retorno[0].equals("true")) { 
                      request.setAttribute("lote",retorno[1]);
                      request.setAttribute("search","ok");
                      CargueDAO cargue = new CargueDAO(cf);
                      int lote = Integer.parseInt(retorno[1]);
                      request.setAttribute("msg","El archivo fue cargado satisfactoriamente en el lote numero "+lote);
                      int icargue = cargue.uploadFile(lote,fileData);
                      cf.closeConnection(cargue.getConn());
                      if(icargue == -1)
                      {
                        request.setAttribute("lote",lote+"");
                        return mapping.findForward("ingreso");
                      }else if(icargue == 0)
                      {
                        request.setAttribute("msg","Ocurrio un error al cargar el archivo..");
                        return mapping.findForward("ingreso");
                      }else{
                        request.setAttribute("msg","Ocurrio un error al cargar el archivo. Revise el registro numero "+icargue+" e intentelo de nuevo...");
                        return mapping.findForward("ingreso");
                      }
                      
                  }else{
                    request.setAttribute("msg","No se pudo cargar el archivo, el nombre ya existe!!");
                    return mapping.findForward("ingreso");
                  }
               }catch(SQLException e){
				System.err.println("/******** TDSUB - cwsub");
				e.printStackTrace();
				System.err.println("TDSUB - cwsub ********/");
                session.setAttribute("msg","No se pudo cargar el archivo..");
                return mapping.findForward("fail");
               }
               
             }
           }
           
          try
          {
            VflexDAO valorFlexDAO = new VflexDAO(cf); 
            tipoCargue = (List)valorFlexDAO.getVflex("TIPOS DE CARGUE AUTOMATICO",1);
            String codeTipoBeneficiario ="";
            String codeTipoBeneficio ="";
            VflexVO vflexVO = null;
            for(int i=0;i<tipoCargue.size();i++)
            {
              vflexVO = (VflexVO)tipoCargue.get(i);
              if(vflexVO.getNombreVflex().equals("BENEFICIARIOS"))
              {
                codeTipoBeneficiario = vflexVO.getCode().toString();
              }else if(vflexVO.getNombreVflex().equals("BENEFICIOS"))
              {
                codeTipoBeneficio = vflexVO.getCode().toString();
              }
            }
            request.setAttribute("codeTipoBeneficiario",codeTipoBeneficiario);
            request.setAttribute("codeTipoBeneficio",codeTipoBeneficio);
            cf.closeConnection(valorFlexDAO.getConn());
          }catch(SQLException e)
          {
			System.err.println("/******** TDSUB - cwsub");
			e.printStackTrace();
			System.err.println("TDSUB - cwsub ********/");
          }
           
        
        }catch (UserException ue) 
        {
				messages.add("msgWarn",  new ActionMessage("loginForm.message."
																			+ ue.getExceptionVO().getId()));
				saveMessages(request, messages);
      	if(ue.getExceptionVO().getId()==AdministrationUserException.ENDED_SESSION)
        {       
              response.sendRedirect(request.getContextPath()+"/index.jsp");
        }
        else if(ue.getExceptionVO().getId()==CommonUserException.NOT_ALLOWED_RESOURCE)
        {
            response.sendRedirect(request.getContextPath()+"/admin/tile/invalidatedResource.jsp");
        }
        else
        {
            return mapping.getInputForward();
        }
      
      }
  
  
  
  
    return mapping.findForward("success");
  }
}